import { createRouter, createWebHistory } from 'vue-router'
import routes from '../router/routes'
import { getAuthorInfo } from '@/api/user'
import store from '@/store'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})



router.beforeEach((to, from, next) => {

  // 无需验证权限的路由
  const pass = ['/login', '/register']

  //可能需要验证权限的路由
  const mabyNeedAuth = ['/index']

  // 如果是无需验证的路由，直接直接通过
  if (pass.includes(to.path)) {
    return next()
  }

  // 游客
  if (store.state.token == '' && mabyNeedAuth.includes(to.path)) {
    return next()
  }


  // 每次跳  转路由之前验证token，并更新登录的用户信息
  getAuthorInfo().then(res => {
    if (res.flag) {
      // 存储登录用户信息
      store.state.loginUserNickname = res.data.nickName
      store.state.username = res.data.username
      store.state.role.push({ authority: res.data.role })
      next()
    } else {
      next('/login')
    }
  })
})



export default router